package com.elinkway.infinitemovies.ui.activity;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableStringBuilder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.elinkway.infinitemovies.config.SettingManage;
import com.elinkway.infinitemovies.download.DownloadHelper;
import com.elinkway.infinitemovies.download.SdcardBroadcastReceiver;
import com.elinkway.infinitemovies.utils.LogCat;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.StorageManager;
import com.elinkway.infinitemovies.utils.UIs;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.le123.ysdq.BuildConfig;
import com.le123.ysdq.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.utils.StorageUtils;

import java.io.File;

public class SettingActivity extends BaseSecondaryActivity implements OnClickListener,OnCheckedChangeListener {
	
	public static final String TAG = "SettingActivity";
	private RelativeLayout mEvnSwitch;
	/*
	 * 接收消息通知布局
	 */
	private RelativeLayout mIfReceivePushLayout = null;
	/*
	 * 清除缓存布局
	 */
	private RelativeLayout set_clean_cache_layout = null;
	/*
	 * 接收消息通知开关项
	 * */
	private ToggleButton mPushSwitchTb = null;
	private TextView cacheSize;
	private SettingManage mSettingManage;
	/*
	 * 3g下载开关
	 */
	private RelativeLayout mdownloadOnlyWifiLayout ;
	private ToggleButton mDownloadOnlyWifiBox;
	/*
	 * sd卡选择
	 */
	private SharedPreferences mSettingSharePreference;
	private Editor mSettingPreferenceEditor;
	private SpannableStringBuilder[] mDownloadPaths;
	private String mDownloadPathItem;
	private TextView downloadPathTip;
	private Dialog mDownloadPathDialog = null;
	private SdcardMountedBroadReceiver mReceiver = null;
	private IntentFilter mIntentFilter = null;
	public static final String DOWNLOAD_PATH = "download_path";
	
	protected static final int CLEAN_COMLETE = 0;




	private RelativeLayout mRelativeDownloadPathSelect;

	private static final int RQUEST_CODE_DOWNLOAD_POSITION = 1;

	private static final int REQUEST_CODE_DOWNLOAD_SHARPNESS = 2;

	private static final int REQUEST_CODE_PLAY_SHARPNESS = 3;

	private TextView mDownloadPathText;

	private RelativeLayout mRelativeSharpnessSelect;

	private TextView mDownloadSharpnessTextView;

	private String mCurrentDownloadSharpness;

	private String mCurrentPlaySharpness;

	private RelativeLayout mRelativeMobileNetWork;

	private ToggleButton mMobileNetWork;

	private RelativeLayout mRelativePlaySharpnessSelect;

	private TextView mPlaySharpnessTextView;

	private RelativeLayout mRelativeClearCache;

	private RelativeLayout mRelativeAboutUs;

	private RelativeLayout mRelativeNotificationMessage;

	private ToggleButton mNotificationMessgeButton;
	
	private Handler mCacheCleanHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(msg.what == CLEAN_COMLETE) {
				UIs.showToast("清除成功！");
				cacheSize.setText("0K");
				set_clean_cache_layout.setEnabled(false);
			}
		}
		
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		super.setActionBarActivityClassName(TAG);
		setContentView(R.layout.activity_setting);
		initActionBar();
		mTitleTv.setText("设置");
		initView();
		initData();
	}


	private void initView() {
		mRelativeNotificationMessage = (RelativeLayout) findViewById(R.id.rl_notification_message);
		mNotificationMessgeButton = (ToggleButton) findViewById(R.id.tb_notification_operation_switch);
		mRelativeAboutUs = (RelativeLayout) findViewById(R.id.rl_about_us);
		mRelativeClearCache = (RelativeLayout) findViewById(R.id.rl_clear_cache);
		mRelativePlaySharpnessSelect = (RelativeLayout) findViewById(R.id.rl_play_sharpness_select);
		mPlaySharpnessTextView = (TextView) findViewById(R.id.tv_play_sharpness);
		mRelativeMobileNetWork = (RelativeLayout) findViewById(R.id.rl_operation_network_download);
		mMobileNetWork = (ToggleButton) findViewById(R.id.tb_operation_switch);
		mEvnSwitch = (RelativeLayout) findViewById(R.id.env_http_switch);
		mEvnSwitch.setVisibility(BuildConfig.ENV_SWITCH ? View.VISIBLE : View.GONE);
		mIfReceivePushLayout = (RelativeLayout) findViewById(R.id.set_layout_new_push_switch_layout);
		set_clean_cache_layout = (RelativeLayout) findViewById(R.id.set_clean_cache_layout);
		mPushSwitchTb = (ToggleButton) findViewById(R.id.set_layout_new_push_switch_tb);
		mdownloadOnlyWifiLayout = (RelativeLayout) findViewById(R.id.set_download_only_wifi_layout);
		mDownloadOnlyWifiBox = (ToggleButton) findViewById(R.id.set_download_only_wifi_checkbox);
		cacheSize = (TextView) findViewById(R.id.clear_cache_text);
		File cache = StorageUtils.getCacheDirectory(getApplicationContext());
		StorageManager manager =  new StorageManager();
		cacheSize.setText(StorageManager.bytes2humanity(manager.getDirectorySize(cache)));
		mEvnSwitch.setOnClickListener(this);
		mIfReceivePushLayout.setOnClickListener(this);
		set_clean_cache_layout.setOnClickListener(this);
		mdownloadOnlyWifiLayout.setOnClickListener(this);
		mDownloadOnlyWifiBox.setOnCheckedChangeListener(this);
		mRelativeMobileNetWork.setOnClickListener(this);
		mMobileNetWork.setOnCheckedChangeListener(this);
		mRelativeClearCache.setOnClickListener(this);
		mRelativeAboutUs.setOnClickListener(this);
		mRelativeNotificationMessage.setOnClickListener(this);
		mNotificationMessgeButton.setOnCheckedChangeListener(this);
	}
	
	private void initData(){
		mSettingManage = new SettingManage(this);
		mPushSwitchTb.setChecked(mSettingManage.isPush());
		mSettingSharePreference = getSharedPreferences(SettingManage.SETTING_RELATIVE_SHAREPREFERENCE ,Context.MODE_PRIVATE);
		mSettingPreferenceEditor = mSettingSharePreference.edit();
		mDownloadOnlyWifiBox.setChecked(mSettingSharePreference.getBoolean(SettingManage.IS_DOWNLOAD_CAN_3G, false));
		mMobileNetWork.setChecked(mSettingSharePreference.getBoolean(SettingManage.IS_DOWNLOAD_CAN_3G, false));
		initSdcardReceiver();
		downloadPathSetting();
		downloadSharpnessSetting();
		playSharpnessSetting();
	}
	
	public static void launch(Activity activity) {
		Intent intent = new Intent(activity, SettingActivity.class);
		UmengEventPoster.postChannelClick(UmengEventPoster.CHANNEL_SETTING);
		activity.startActivity(intent);
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
			case R.id.rl_notification_message:
				mSettingManage.setPushToggleButtonState(mNotificationMessgeButton);
				break;
			case R.id.rl_about_us:
				AboutUsActivity.launch(SettingActivity.this);
				break;
			case R.id.rl_clear_cache:
				new Thread(){
					@Override
					public void run() {
						ImageLoader uil = ImageLoader.getInstance();
						uil.clearMemoryCache();
						uil.clearDiscCache();
						mCacheCleanHandler.sendEmptyMessage(CLEAN_COMLETE);
						super.run();
					}
				}.start();
				break;
			case R.id.rl_operation_network_download:
				mSettingManage.setToggleButtonState(mMobileNetWork, mSettingPreferenceEditor, SettingManage.IS_DOWNLOAD_CAN_3G);
				break;
			case R.id.env_http_switch:
				EnvironmentSwitchActivity.launch(SettingActivity.this);
				break;
			case R.id.set_layout_new_push_switch_layout:
				mSettingManage.setPushToggleButtonState(mPushSwitchTb);
				break;
			case R.id.set_download_only_wifi_layout:
				mSettingManage.setToggleButtonState(mDownloadOnlyWifiBox, mSettingPreferenceEditor, SettingManage.IS_DOWNLOAD_CAN_3G);
				break;
			case R.id.set_clean_cache_layout:
				new Thread(){
				@Override
				public void run() {
					ImageLoader uil = ImageLoader.getInstance();
					uil.clearMemoryCache();
					uil.clearDiscCache();
					mCacheCleanHandler.sendEmptyMessage(CLEAN_COMLETE);
					super.run();
				}
			}.start();
				break;
		}
		
	}
	@Override
	protected void onResume() {
		super.onResume();
		set_clean_cache_layout.setEnabled(true);
		if(null != mReceiver && null != mIntentFilter) {
			registerReceiver(mReceiver, mIntentFilter);
		}
	}
	@Override
	protected void onPause() {
		super.onPause();
		if(null != mReceiver) {
			unregisterReceiver(mReceiver);
		}
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch (buttonView.getId()) {
		    case R.id.set_download_only_wifi_checkbox:
//			    mSettingManage.setToggleButtonPreference(isChecked,mSettingPreferenceEditor,SettingManage.IS_DOWNLOAD_CAN_3G);
//			    mSettingManage.popIfContinueDownloadDialog(isChecked);
		        mSettingManage.sendBroadCast(isChecked);
			    break;
		    case R.id.set_layout_new_push_switch_tb:
			    mSettingManage.setPushToggleButtonPreference(isChecked);
			    break;
		    case R.id.tb_operation_switch:
				mSettingManage.setToggleButtonPreference(isChecked,mSettingPreferenceEditor,SettingManage.IS_DOWNLOAD_CAN_3G);
			    mSettingManage.sendBroadCast(isChecked);
				break;
			case R.id.tb_notification_operation_switch:
				mSettingManage.setPushToggleButtonPreference(isChecked);
				break;
			default:
				break;
		}
		
	}
	/**
	 * 播放清晰度选择
	 */
	private void playSharpnessSetting() {
		mRelativePlaySharpnessSelect = (RelativeLayout) findViewById(R.id.rl_play_sharpness_select);
		mPlaySharpnessTextView = (TextView) findViewById(R.id.tv_play_sharpness);
		mSettingSharePreference = getSharedPreferences(SettingManage.SETTING_RELATIVE_SHAREPREFERENCE, Context.MODE_PRIVATE);
		mCurrentPlaySharpness = mSettingSharePreference
				.getString(MoviesConstant.PLAY_SHARPNESS_SELECT, "2");
		mPlaySharpnessTextView.setText(MoviesConstant.SHARPNESS[
				Integer.parseInt(mCurrentPlaySharpness)]);
		mRelativePlaySharpnessSelect.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mSettingSharePreference != null) {
					mSettingPreferenceEditor = mSettingSharePreference.edit();
					mCurrentPlaySharpness = mSettingSharePreference.getString(
							MoviesConstant.PLAY_SHARPNESS_SELECT, MoviesConstant.SUPER);
				}
				Intent intent = new Intent(SettingActivity.this, DownloadSharpnessSelectActivity.class);
				LogCat.e(TAG, "mCurrentPlaySharpness " + mCurrentPlaySharpness);
				intent.putExtra(MoviesConstant.DOWNLOAD_SHARPNESS_SELECT, mCurrentPlaySharpness);
				startActivityForResult(intent, REQUEST_CODE_PLAY_SHARPNESS);
			}
		});
	}

	/**
	 * 下载清晰度选择
	 */
	private void downloadSharpnessSetting() {
		mRelativeSharpnessSelect = (RelativeLayout) findViewById(R.id.download_sharpness_select);
		mDownloadSharpnessTextView = (TextView) findViewById(R.id.tv_download_sharpness);
		mSettingSharePreference = getSharedPreferences(SettingManage.SETTING_RELATIVE_SHAREPREFERENCE, Context.MODE_PRIVATE);
		mCurrentDownloadSharpness = mSettingSharePreference
				.getString(MoviesConstant.DOWNLOAD_SHARPNESS_SELECT, MoviesConstant.SUPER);
		mDownloadSharpnessTextView.setText(MoviesConstant.SHARPNESS[
				Integer.parseInt(mCurrentDownloadSharpness)]);
		mRelativeSharpnessSelect.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mSettingSharePreference != null) {
					mSettingPreferenceEditor = mSettingSharePreference.edit();
					mCurrentDownloadSharpness = mSettingSharePreference.getString(
							MoviesConstant.DOWNLOAD_SHARPNESS_SELECT, MoviesConstant.SUPER);
				}
				Intent intent = new Intent(SettingActivity.this, DownloadSharpnessSelectActivity.class);
				LogCat.e(TAG, "downloadSharpnessSetting " + mCurrentDownloadSharpness);
				intent.putExtra(MoviesConstant.DOWNLOAD_SHARPNESS_SELECT, mCurrentDownloadSharpness);
				startActivityForResult(intent, REQUEST_CODE_DOWNLOAD_SHARPNESS);
			}
		});
	}
	
	 /**
     * 下载路径选择初始化操作
     */
    private void downloadPathSetting() {
		RelativeLayout downloadPath = (RelativeLayout) findViewById(R.id.set_layout_download_path_layout);
		downloadPathTip = (TextView) findViewById(R.id.download_path_tip);
			mDownloadPaths = DownloadHelper.getShowingItems();
			mSettingSharePreference = getSharedPreferences(SettingManage.SETTING_RELATIVE_SHAREPREFERENCE, Context.MODE_PRIVATE);
			mDownloadPathItem = mSettingSharePreference.getString(DOWNLOAD_PATH, "0");
		    LogUtils.e(TAG, "default download path is " + mDownloadPathItem);
			if(null == mDownloadPaths || Integer.parseInt(mDownloadPathItem) >= mDownloadPaths.length)
				return;
			downloadPathTip.setText(mDownloadPaths[Integer.parseInt(mDownloadPathItem)].toString().substring(0,mDownloadPaths[Integer.parseInt(mDownloadPathItem)].toString().indexOf("\n")));
			downloadPath.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					showDownloadPathDialog();
				}
			});

		mRelativeDownloadPathSelect = (RelativeLayout) findViewById(R.id.download_path_select);
		mDownloadPathText = (TextView) findViewById(R.id.tv_download_path);
		if ("0".equals(mDownloadPathItem)) {
			mDownloadPathText.setText(getResources().getString(R.string.download_path_local));
		} else {
            mDownloadPathText.setText(getResources().getString(R.string.download_outside_sd_path));
		}
		mRelativeDownloadPathSelect.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(SettingActivity.this, DownloadSelectActivity.class);
				LogCat.e(TAG, "download path length " + mDownloadPaths.length);
				intent.putExtra(MoviesConstant.DOWNLOAD_PATH_SELECT, mDownloadPaths.length);
				if (mSettingSharePreference != null) {
					mSettingPreferenceEditor = mSettingSharePreference.edit();
					mDownloadPathItem = mSettingSharePreference.getString(DOWNLOAD_PATH, "0");
				}
				intent.putExtra(MoviesConstant.DOWNLOAD_PATH, mDownloadPathItem);
				startActivityForResult(intent, RQUEST_CODE_DOWNLOAD_POSITION);
			}
		});





//		}
	}
    protected void showDownloadPathDialog() {
		mSettingPreferenceEditor = mSettingSharePreference.edit();
		mDownloadPathItem = mSettingSharePreference.getString(DOWNLOAD_PATH, "0");
		mDownloadPathDialog = new AlertDialog.Builder(this)
        	.setTitle(getString(R.string.download_paths))
        	.setSingleChoiceItems(mDownloadPaths, Integer.parseInt(mDownloadPathItem), new DialogInterface.OnClickListener() {
        		public void onClick(DialogInterface dialog, int which) {
        			LogUtils.i("down", "" + mDownloadPaths[which] + " " + which);
        			mSettingPreferenceEditor.putString(DOWNLOAD_PATH, String.valueOf(which));
        			mSettingPreferenceEditor.commit();
    				downloadPathTip.setText(mDownloadPaths[which].toString().substring(0,mDownloadPaths[which].toString().indexOf("\n")));
    				DownloadHelper.RESTORE_FLAG = false;
    				DownloadHelper.DOWNLOAD_FILEPATH_NUMBER = which;
    				DownloadHelper.saveReallyDownloadPath(which);
    				DownloadHelper.storageAllExtSdcardPath();
    				dialog.dismiss();
            }
        })
       .create();
		mDownloadPathDialog.show();
	}
    class SdcardMountedBroadReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent != null) {
				if(context==null)
					return;
				String action = intent.getAction();
				if(SdcardBroadcastReceiver.SDCARD_CHANGE.equals(action)) {
					downloadPathSetting();
				}
			}
		}
	}
	
	private void initSdcardReceiver() {
		mReceiver = new SdcardMountedBroadReceiver();
		mIntentFilter = new IntentFilter(SdcardBroadcastReceiver.SDCARD_CHANGE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		LogUtils.e(TAG, "onActivityResult " + requestCode + " " + resultCode );
		if (RQUEST_CODE_DOWNLOAD_POSITION == requestCode) {
			if (RQUEST_CODE_DOWNLOAD_POSITION == resultCode && mDownloadPathText != null) {
				int which = 0;
				if ("0".equals(data.getStringExtra(MoviesConstant.DOWNLOAD_PATH))) {
					LogUtils.e(TAG, "download_path_local");
					which = 0;
					mDownloadPathText.setText(getResources().getString(R.string.download_path_local));
				} else {
					which = 1;
					LogUtils.e(TAG, "download_outside_sd_path");
				    mDownloadPathText.setText(getResources().getString(R.string.download_outside_sd_path));
				}
				mSettingPreferenceEditor = mSettingSharePreference.edit();
				mSettingPreferenceEditor.putString(DOWNLOAD_PATH, data.getStringExtra(MoviesConstant.DOWNLOAD_PATH));
				mSettingPreferenceEditor.commit();
				DownloadHelper.RESTORE_FLAG = false;
				DownloadHelper.DOWNLOAD_FILEPATH_NUMBER = which;
				DownloadHelper.saveReallyDownloadPath(which);
				DownloadHelper.storageAllExtSdcardPath();
			}
		} else if (REQUEST_CODE_DOWNLOAD_SHARPNESS == requestCode) {
			if (REQUEST_CODE_DOWNLOAD_SHARPNESS == resultCode && mDownloadSharpnessTextView != null) {
                mDownloadSharpnessTextView.setText(MoviesConstant.SHARPNESS[Integer.parseInt(
						data.getStringExtra(MoviesConstant.DOWNLOAD_SHARPNESS_SELECT))]);
				mSettingPreferenceEditor = mSettingSharePreference.edit();
				mSettingPreferenceEditor.putString(MoviesConstant.DOWNLOAD_SHARPNESS_SELECT,
						data.getStringExtra(MoviesConstant.DOWNLOAD_SHARPNESS_SELECT));
				mSettingPreferenceEditor.commit();
			}
		} else if (REQUEST_CODE_PLAY_SHARPNESS == requestCode) {
			if (REQUEST_CODE_DOWNLOAD_SHARPNESS == resultCode && mPlaySharpnessTextView != null) {
				mPlaySharpnessTextView.setText(MoviesConstant.SHARPNESS[Integer.parseInt(
						data.getStringExtra(MoviesConstant.DOWNLOAD_SHARPNESS_SELECT))]);
				mSettingPreferenceEditor = mSettingSharePreference.edit();
				mSettingPreferenceEditor.putString(MoviesConstant.PLAY_SHARPNESS_SELECT,
						data.getStringExtra(MoviesConstant.DOWNLOAD_SHARPNESS_SELECT));
				mSettingPreferenceEditor.commit();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}